const express = require("express");
const { jiaoModel } = require("../model/models");
const mongoose = require("mongoose"); // 引入 mongoose
const router = express.Router();

router.post("/getfirend", async (req, res) => {
  let ids = req.body;
  let data = await jiaoModel.find({ _id: { $in: ids } });
  res.send(data);
});

router.post("/update_password", async (req, res) => {
  const { id, newPassword } = req.body;
  console.log(req.body);
  // let ids = req.body;
  let data = await jiaoModel.updateOne({ _id: id }, { $set: { pwd: newPassword } });
  res.send({ code: 200 });
});

router.get("/loginInfo", async (req, res) => {
  let data = await jiaoModel.findOne();
  res.send({
    code: 200,
    data,
  });
});

// 更新用户信息
router.post("/switch_img", async (req, res) => {
  const { name, image } = req.body;
  let user = await jiaoModel.findOne();
  user.name = name;
  user.img_url = image;
  console.log(user);
  await user.save();
  res.send({ code: 200 });
});

// 更新星座信息
router.put("/switch_lable", async (req, res) => {
  const { labelsString } = req.body;
  let user = await jiaoModel.findOne();
  const result = await jiaoModel.updateOne(
    { _id: user._id },
    { $set: { xingzuo: labelsString } }
  );
  if (result.nModified === 0) {
    return res.status(400).send({ code: 400, message: "No updates were made" });
  }
  res.send({ code: 200 });
});

// 发送动态
router.post("/send", async (req, res) => {
  const { img, text, latitude, longitude, address, is_ding } = req.body;
  try {
    let info = await jiaoModel.findOne();

    const newDongTaiBase = {
      img,
      text,
      tage: [],
      tages: [],
      zhans: 0,
      latitude,
      longitude,
      is_ding,
    };
    const newDongTai = is_ding
      ? { ...newDongTaiBase, address }
      : { ...newDongTaiBase, address: "" };
    info.dong_tai.push(newDongTai);
    await info.save();

    res.send({
      code: 200,
      message: "Data added successfully",
      data: info,
    });
  } catch (e) {
    console.log(e);
  }
});

// 获取指定动态
router.put("/One", async (req, res) => {
  const { id } = req.body;

  // 检查 id 是否为有效的 ObjectId
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({ code: 400, message: "Invalid ID format" });
  }

  const objectId = new mongoose.Types.ObjectId(id);

  try {
    const data = await jiaoModel.findOne();
    if (!data) {
      return res.status(404).send({ code: 404, message: "User not found" });
    }

    const targetDongTai = data.dong_tai.find(
      (item) => item._id.toString() === objectId.toString()
    );

    if (targetDongTai) {
      res.send({
        code: 200,
        message: "Data found successfully",
        data: targetDongTai,
      });
    } else {
      res.send({
        code: 404,
        message: "Dong Tai not found",
      });
    }
  } catch (err) {
    console.error(err);
    res.status(500).send({ code: 500, message: "Internal server error" });
  }
});

module.exports = router;
